package org.jeecg.modules.kc.controller;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fasterxml.jackson.annotation.JsonFormat;
import org.apache.commons.lang3.ObjectUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.TokenUtils;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.kc.dto.SupplierInGoodsDto;
import org.jeecg.modules.kc.entity.KcGoods;
import org.jeecg.modules.kc.entity.KcGoodsType;
import org.jeecg.modules.kc.entity.KcSupplier;
import org.jeecg.modules.kc.entity.KcSupplierInGoods;
import org.jeecg.modules.kc.service.IKcGoodsService;
import org.jeecg.modules.kc.service.IKcGoodsTypeService;
import org.jeecg.modules.kc.service.IKcSupplierInGoodsService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.modules.rooms.entity.CesGoods;
import org.jeecg.modules.rooms.entity.CesGoodsUnit;
import org.jeecg.modules.rooms.entity.CesStockType;
import org.jeecg.modules.rooms.service.CesGoodsServiceImpl;
import org.jeecg.modules.rooms.service.CesGoodsUnitServiceImpl;
import org.jeecg.modules.rooms.service.CesStockTypeServiceImpl;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.apache.shiro.authz.annotation.RequiresPermissions;

 /**
 * @Description: kc_supplier_in_goods
 * @Author: jeecg-boot
 * @Date:   2023-04-18
 * @Version: V1.0
 */
@Api(tags="kc_supplier_in_goods")
@RestController
@RequestMapping("/kc/kcSupplierInGoods")
@Slf4j
public class KcSupplierInGoodsController extends JeecgController<KcSupplierInGoods, IKcSupplierInGoodsService> {
	@Autowired
	private IKcSupplierInGoodsService kcSupplierInGoodsService;
	@Autowired
	private IKcGoodsService kcGoodsService;
	 @Autowired
	 private CesStockTypeServiceImpl cesStockTypeTypeService;
	@Autowired
	private CesGoodsServiceImpl goodsService;
	@Autowired
	private IKcGoodsTypeService kcGoodsTypeService;
	 @Autowired
	 private CesGoodsUnitServiceImpl cesGoodsUnitService;

	/**
	 * 分页列表查询
	 *
	 * @param kcSupplierInGoods
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "kc_supplier_in_goods-分页列表查询")
	@ApiOperation(value="kc_supplier_in_goods-分页列表查询", notes="kc_supplier_in_goods-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<KcSupplierInGoods>> queryPageList(KcSupplierInGoods kcSupplierInGoods,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		Page<KcSupplierInGoods> page = new Page<KcSupplierInGoods>(pageNo, pageSize);
		IPage<KcSupplierInGoods> pageList = kcSupplierInGoodsService.supplierInGoodsList(page, kcSupplierInGoods.getHotelId(), kcSupplierInGoods.getGoodsName(), kcSupplierInGoods.getGoodsTypeId(), kcSupplierInGoods.getSupplierId());
		return Result.OK(pageList);
	}

	 /**
	  * 供货/待供货商品分页列表查询
	  * @param cesGoods
	  * @param pageNo
	  * @param pageSize
	  * @param supplierId 供应商id
	  * @param inGoods 是否供货商品
	  * @param req
	  * @return
	  */
	 //@AutoLog(value = "kc_supplier_in_goods-分页列表查询")
	 @ApiOperation(value="kc_supplier_in_goods-分页列表查询", notes="kc_supplier_in_goods-分页列表查询")
	 @GetMapping(value = "/goodsList")
	 public Result<IPage<CesGoods>> goodsList(CesGoods cesGoods,
														   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
														   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
											 @RequestParam(name="supplierId",required = true) String supplierId,
											 @RequestParam(name="inGoods",required = true) @JsonFormat() Boolean inGoods,
														   HttpServletRequest req) {
		 LambdaQueryWrapper<CesGoods> queryWrapper = QueryGenerator.initQueryWrapper(cesGoods, req.getParameterMap()).lambda();
		 queryWrapper.eq(CesGoods::getInvalid,0);
		 if (ObjectUtils.isEmpty(supplierId)) {
			 return Result.error("请传入供应商id");
		 }
		 if (inGoods) {
			 queryWrapper.exists("select 1 from kc_supplier_in_goods where goods_id=ces_goods.id and supplier_id=" + supplierId);
		 } else {
			 queryWrapper.notExists("select 1 from kc_supplier_in_goods where goods_id=ces_goods.id and supplier_id=" + supplierId);
		 }
		 Page<CesGoods> page = new Page<CesGoods>(pageNo, pageSize);
		 IPage<CesGoods> pageList = goodsService.page(page, queryWrapper);
		 List<CesGoodsUnit> goodsUnits = cesGoodsUnitService.list();
		 pageList.getRecords().forEach(item -> {
			 CesStockType cesStockType = cesStockTypeTypeService.getById(item.getGoodType());
			 if (cesStockType != null) {
				 item.setGoodTypeName(cesStockType.getName());
			 }
			 LambdaQueryWrapper<KcSupplierInGoods> lambdaQueryWrapper = new LambdaQueryWrapper<>();
			 lambdaQueryWrapper.eq(KcSupplierInGoods::getSupplierId, supplierId);
			 lambdaQueryWrapper.eq(KcSupplierInGoods::getGoodsId, item.getId());
			 KcSupplierInGoods kcSupplierInGoods = kcSupplierInGoodsService.getOne(lambdaQueryWrapper);
			 if (kcSupplierInGoods != null) {
				 item.setSupplierInGoodsId(kcSupplierInGoods.getId());
			 }

			 Optional<CesGoodsUnit> goodsUnit = goodsUnits.stream().filter(units -> units.getId().equals(item.getGoodUnit())).findFirst();
			 goodsUnit.ifPresent(e -> item.setGoodsUnitName(e.getName()));
		 });
		 return Result.OK(pageList);
	 }

	/**
	 *   添加
	 *
	 * @param dto
	 * @return
	 */
	@AutoLog(value = "kc_supplier_in_goods-添加")
	@ApiOperation(value="kc_supplier_in_goods-添加", notes="kc_supplier_in_goods-添加")
	//@RequiresPermissions("kc:kc_supplier_in_goods:add")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody SupplierInGoodsDto dto) {
		if (ObjectUtils.isEmpty(dto.getGoodsIds())) {
			return Result.error("请先选择商品");
		}
		List<KcSupplierInGoods> list = new ArrayList<>();
		for (String goodsId : dto.getGoodsIds()) {
			LambdaQueryWrapper<KcSupplierInGoods> lambdaQueryWrapper = new LambdaQueryWrapper<>();
			lambdaQueryWrapper.eq(KcSupplierInGoods::getGoodsId, goodsId);
			lambdaQueryWrapper.eq(KcSupplierInGoods::getSupplierId, dto.getSupplierId());
			Long count = kcSupplierInGoodsService.count(lambdaQueryWrapper);
			if (count <= 0) {
				KcSupplierInGoods kcSupplierInGoods = new KcSupplierInGoods();
				kcSupplierInGoods.setTenantId(TokenUtils.currentTenantId());
				kcSupplierInGoods.setHotelId(dto.getHotelId());
				kcSupplierInGoods.setGoodsId(goodsId);
				kcSupplierInGoods.setPrice(BigDecimal.ZERO);
				kcSupplierInGoods.setSupplierId(dto.getSupplierId());
				list.add(kcSupplierInGoods);
			}
		}
		kcSupplierInGoodsService.saveBatch(list);
		return Result.OK("添加成功！");
	}

	/**
	 *  编辑
	 *
	 * @param kcSupplierInGoods
	 * @return
	 */
	@AutoLog(value = "kc_supplier_in_goods-编辑")
	@ApiOperation(value="kc_supplier_in_goods-编辑", notes="kc_supplier_in_goods-编辑")
	//@RequiresPermissions("kc:kc_supplier_in_goods:edit")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody List<KcSupplierInGoods> kcSupplierInGoods) {
		kcSupplierInGoodsService.updateBatchById(kcSupplierInGoods);
		return Result.OK("编辑成功!");
	}

	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "kc_supplier_in_goods-通过id删除")
	@ApiOperation(value="kc_supplier_in_goods-通过id删除", notes="kc_supplier_in_goods-通过id删除")
	//@RequiresPermissions("kc:kc_supplier_in_goods:delete")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		kcSupplierInGoodsService.removeById(id);
		return Result.OK("删除成功!");
	}

	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "kc_supplier_in_goods-批量删除")
	@ApiOperation(value="kc_supplier_in_goods-批量删除", notes="kc_supplier_in_goods-批量删除")
	//@RequiresPermissions("kc:kc_supplier_in_goods:deleteBatch")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.kcSupplierInGoodsService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "kc_supplier_in_goods-通过id查询")
	@ApiOperation(value="kc_supplier_in_goods-通过id查询", notes="kc_supplier_in_goods-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<KcSupplierInGoods> queryById(@RequestParam(name="id",required=true) String id) {
		KcSupplierInGoods kcSupplierInGoods = kcSupplierInGoodsService.getById(id);
		if(kcSupplierInGoods==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(kcSupplierInGoods);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param kcSupplierInGoods
    */
    //@RequiresPermissions("kc:kc_supplier_in_goods:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, KcSupplierInGoods kcSupplierInGoods) {
        return super.exportXls(request, kcSupplierInGoods, KcSupplierInGoods.class, "kc_supplier_in_goods");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    //@RequiresPermissions("kc:kc_supplier_in_goods:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, KcSupplierInGoods.class);
    }

}
